package com.rookie.im.core.server.handler;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.rookie.im.core.codec.proto.Message;
import com.rookie.im.core.codec.proto.MessageHead;
import com.rookie.im.core.codec.proto.MessagePack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketMessageDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {

    private static final int HEADER_LENGTH = 28;
	@Override
	protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg, List<Object> out) throws Exception {
		ByteBuf content = msg.content();
		if (content.readableBytes() < HEADER_LENGTH) {
			out.add(msg);
			log.info("Message length less then {}", HEADER_LENGTH);
            return;
		}
		int startIndex = content.readerIndex();
		MessageHead head = new MessageHead();
		int offset = 0;
		head.setCommand(content.getInt(startIndex + offset));
		offset += 4;
		head.setVersion(content.getInt(startIndex + offset));
		offset += 4;
		head.setClientType(content.getInt(startIndex + offset));
		offset += 4;
		head.setMessageType(content.getInt(startIndex + offset));
		offset += 4;
		head.setAppId(content.getInt(startIndex + offset));
		offset += 4;
		head.setImeiLength(content.getInt(startIndex + offset));
		offset += 4;
		head.setLength(content.getInt(startIndex + offset));
		
		if (content.readableBytes() < HEADER_LENGTH + head.getImeiLength() + head.getLength()) {
			content.resetReaderIndex();
			out.add(msg);
			return;
		}
		content.skipBytes(HEADER_LENGTH);
		byte[] imeiData = new byte[head.getImeiLength()];
		content.readBytes(imeiData);
		String imei = new String(imeiData, CharsetUtil.UTF_8);
		head.setImei(imei);
		byte[] bodyData = new byte[head.getLength()];
		content.readBytes(bodyData);
		
		Message message = new Message();
		message.setMessageHead(head);
		// json
		if (0x0 == head.getMessageType()) {
			String bodyString = new String(bodyData, CharsetUtil.UTF_8);
			message.setMessagePack(new MessagePack(imei, JSONObject.parseObject(bodyString)));
			out.add(message);
			return;
		}
		log.info("未匹配到消息类型,向下传递");
		content.resetReaderIndex();
		out.add(msg);
		return;
	}

}
